import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Card} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {PAGE, FIXED_COLUMN_WIDTH, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';
import {getModes, addMode, updateMode, abandonMode, exportMode} from './api';
import {PERMISSION} from './constants';
import Export from '../common/Export';
import {hasPermissions} from './utils';
import routes from './routes';
import Return from '../common/Return';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
import RepairModeEdit from './RepairModeEdit';
const FormItem = Form.Item;
const ButtonGroup = Button.Group;
const EMPTY_ARRAY = [];
class RepairMode extends React.PureComponent {
    state = {
        condition: {
            pageIndex: PAGE.index,
            pageSize: PAGE.smallSize
        },
        currentCondition: {},
        loading: false,
        data: EMPTY_ARRAY,
        total: 0,
        error: false,
        showPanel: false,
        currentId: '',
    };

    componentDidMount() {
        this.handleQueryBtnClick();
    }
    handleConditionChange = (value, name) => this.setState({condition: Object.assign({}, this.state.condition, {[name]: value})});

    handleQueryBtnClick = () => this.onQuery(Object.assign({}, this.state.currentCondition, this.state.condition, {pageIndex: PAGE.index}));

    handleFilterPressEnter = (value, name) => this.setState(() => ({
        condition: Object.assign({}, this.state.condition, {[name]: value
        })}), this.handleQueryBtnClick);

    handleTableChange = (pagination, filters, sorter) => {
        const query = {
            sortField: null,
            isDesc: null
        };
        if(pagination.pageSize)
            query.pageSize = pagination.pageSize;
        if(pagination.current)
            query.pageIndex = pagination.current - 1;
        if(sorter.order && sorter.field) {
            query.sortField = sorter.field;
            query.isDesc = sorter.order === 'descend';
        }
        this.setState({
            condition: {
                ...this.state.condition,
                pageSize: query.pageSize
            }
        });
        this.onQuery(Object.assign({}, this.state.currentCondition, query));
    };

    handleAbandon = id => {
        this.setState({
            loading: true
        });
        const {rowVersion} = this.state.data.find(item => item.id === id);
        return abandonMode(id, {
            rowVersion
        }).then(success => {
            this.setState({
                loading: false
            });
            if(success)
                this.handleQueryBtnClick();
        });
    };

    isSortOrder = propName => this.state.currentCondition.sortField === propName && (this.state.currentCondition.isDesc ? 'descend' : 'ascend');
    
    onClickEdit = e => {
        const {id} = e.target.dataset;
        this.setState({
            currentId: id,
            showPanel: true
        });
    }

    onClickAdd = () => {
        this.setState({
            currentId: '',
            showPanel: true
        });
    }

    onCancel = () => {
        this.setState({
            currentId: '',
            showPanel: false
        });
    }

    onSubmit = data => {
        const {id, rowVersion, description, code, name} = data;
        if(!id)
            return addMode({
                code,
                name,
                description
            }).then(success => {
                this.setState({
                    loading: false,
                });
                if(success) {
                    this.onCancel();
                    this.handleQueryBtnClick();
                }
                return success;
            });
        return updateMode(id, {
            rowVersion,
            description,
        }).then(success => {
            this.setState({
                loading: false,
            });
            if(success) {
                this.onCancel();
                this.handleQueryBtnClick();
            }
            return success;
        });
    }
    onQuery = conditions => {
        this.setState({loading: true});
        return getModes(Object.assign(conditions, this.props.conditions)).then(result => this.setState({
            loading: false,
            error: result.ok,
            data: result.ok ? result.data.content : EMPTY_ARRAY,
            total: result.ok ? result.data.totalElements : 0,
            currentCondition: conditions,
        }));
    };

    onReset = () => {
        this.setState({condition: Object.assign({}, this.state.condition, {
            code: '',
            name: ''
        })});
    }

    onClickExport = () => {
        const {code, name} = this.state.condition;
        const {sortField, isDesc} = this.state.currentCondition;
        return exportMode({
            code,
            name,
            sortField,
            isDesc,
        });
    }

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.code',
                    defaultMessage: '编号'
                }),
                sorter: true,
                sortOrder: this.isSortOrder('code'),
                dataIndex: 'code'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.name',
                    defaultMessage: '名称'
                }),
                sorter: true,
                sortOrder: this.isSortOrder('name'),
                dataIndex: 'name'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.description',
                    defaultMessage: '描述'
                }),
                dataIndex: 'description'
            }
        ];

        const pagination = {
            total: this.state.total,
            current: this.state.currentCondition.pageIndex + 1,
            pageSize: this.state.currentCondition.pageSize,
            ...PAGINATION_OPTIONS
        };
        if(hasPermissions(this.props.permissions, PERMISSION.modeManage))
            columns.push({
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: 'update',
                            children: (
                                <a key="update" data-id={r.id} onClick={this.onClickEdit}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </a>
                            ),
                        },
                        {
                            id: 'abandon',
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'repairMode.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {this.props.intl.formatMessage({
                                            id: 'repairMode.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            });
        const detail = this.state.data.find(item => item.id === this.state.currentId) || {};

        return (
            <div>
                <RepairModeEdit
                    detail={detail}
                    onSubmit={this.onSubmit}
                    onCancel={this.onCancel}
                    showPanel={this.state.showPanel} />
                <Card>
                    <Form className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'repairMode.form.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="code"
                                        value={this.state.condition.code}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleConditionChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'repairMode.form.name',
                                        defaultMessage: '名称'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="name"
                                        value={this.state.condition.name}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleConditionChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row className="operation-buttons">
                            <Col span={16}>
                                <Button type="primary"
                                    loading={this.state.loading}
                                    onClick={this.handleQueryBtnClick}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                                <Button key="clear" onClick={this.onReset}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.btn.reset',
                                        defaultMessage: '重置'
                                    })}
                                </Button>
                            </Col>
                            {hasPermissions(this.props.permissions, PERMISSION.modeManage)
                                ? <Col span={8} className="col-align-right">
                                    <ButtonGroup>
                                        <Button key="import" href={`#${routes.modeImport.url()}`}>
                                            {this.props.intl.formatMessage({
                                                id: 'repairMode.btn.modeImport',
                                                defaultMessage: '导入'
                                            })}
                                        </Button>
                                        <Export key="export" exportRequest={this.onClickExport} />
                                    </ButtonGroup>
                                    <Button key="add" type="primary" onClick={this.onClickAdd}>
                                        {this.props.intl.formatMessage({
                                            id: 'repairMode.btn.add',
                                            defaultMessage: '新增'
                                        })}
                                    </Button>
                                </Col> : null}
                        </Row>
                    </Form>
                </Card>
                <Card>
                    <Table
                        className="white-space-nowrap"
                        rowKey="id"
                        dataSource={this.state.data}
                        columns={columns}
                        loading={this.state.loading}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                        {...TABLE}
                        locale={{emptyText: this.state.error ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT}} />
                </Card>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}

RepairMode.propTypes = {
    conditions: PropTypes.object,
    intl: PropTypes.object,
    permissions: PropTypes.array,
};

import {connect} from 'react-redux';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onCancel: () => {
        ownProps.history.goBack();
    },
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(RepairMode));
